Reference
C Library
IOstream Library
Strings library
STL Containers
STL Algorithms
Miscellaneous
STL Containers
bitset
deque
list
map
multimap
multiset
priority_queue
queue
set
stack
vector
map
comparison operators
map::map
map::~map
member functions:
map::begin
map::clear
map::count
map::empty
map::end
map::equal_range
map::erase
map::find
map::get_allocator
map::insert
map::key_comp
map::lower_bound
map::max_size
map::operator=
map::operator[]
map::rbegin
map::rend
map::size
map::swap
map::upper_bound
map::value_comp


map::operator[]

public member function
T& operator[] ( const key_type& x );

Access element

If x matches the key of an element in the container, the function returns a reference to its mapped value.

If x does not match the key of any element in the container, the function inserts a new element with that key and returns a reference to its mapped value. Notice that this always increases the map size by one, even if no mapped value is assigned to the element (the element is constructed using its default constructor).

A call to this function is equivalent to:
(*((this->insert(make_pair(x,T()))).first)).second

Parameters

x
Key value of the element whose mapped value is accessed.
key_type is a member type defined in map containers as an alias of Key, which is the first template parameter and the type of the element keys.

Return value

A reference to the element with a key value equal to x.
T is the second template parameter, which defines the type of the mapped values in the container.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// accessing mapped values
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main ()
{
  map<char,string> mymap;
  mymap['a']="an element";
  mymap['b']="another element";
  mymap['c']=mymap['b'];
  cout << "mymap['a'] is " << mymap['a'] << endl;
  cout << "mymap['b'] is " << mymap['b'] << endl;
  cout << "mymap['c'] is " << mymap['c'] << endl;
  cout << "mymap['d'] is " << mymap['d'] << endl;
  cout << "mymap now contains " << (int) mymap.size() << " elements." << endl;
  return 0;
}


Notice how the last access (to element 'd') inserts a new element in the set with that key and initialized to its default value (an empty string) even though it is accessed only to retrieve its value. Member function map::find does not produce this effect.
Output:
mymap['a'] is an element
mymap['b'] is another element
mymap['c'] is another element
mymap['d'] is
mymap now contains 4 elements.

Complexity

Logarithmic in size.

See also